#!/usr/bin/ruby
#-*- coding: UTF-8 -*-
require 'xcodeproj'
Encoding.default_external = Encoding::UTF_8
Encoding.default_internal = Encoding::UTF_8

ruby_file_path = ARGV[0]
iReSignAppPath = ARGV[1]

$ruby_file = File.new("#{ruby_file_path}","w")
system("chmod -R 777 #{ruby_file_path}")

def find_certification_name (team_identifier)
	tempPath = "#{File.dirname(__FILE__)}/forAddSdkCertificate.txt"
	system("security find-certificate -a -c \"iPhone Developer\" > #{tempPath}")
	file_txt = File.read(tempPath)
	system("rm -rf #{tempPath}")

	attributes_array = file_txt.split("attributes:")
	code_sign_file_name = ""
	attributes_array.each { |attribute|
		if attribute.include? team_identifier
			# puts attribute
			code_sign_file_name = attribute.match(/(iPhone Developer: .* \(.*\))/)
			break;
		end
	}
	return code_sign_file_name
end

def getTeamName (file_path,provision_type)
	folder = File.dirname(file_path)
    tempPath = "#{folder}/forAddSdkCertificate.plist"
	system("security cms -D -i #{file_path} > #{tempPath}")
	file_content_hash = Xcodeproj::Plist.read_from_path(tempPath)
	system("rm -rf #{tempPath}")
	team_identifier = file_content_hash['TeamIdentifier'].first
	team_name = file_content_hash["TeamName"]
	name = file_content_hash["Name"]

	code_sign_identify = ""
	if provision_type == "Developer"
		code_sign_identify = find_certification_name team_identifier
	else
		code_sign_identify = "iPhone #{provision_type}: #{team_name} (#{team_identifier})"
	end
	return code_sign_identify,name
end

$ruby_file.puts "#!/usr/bin/ruby
#-*- coding: UTF-8 -*-
require 'xcodeproj'
Encoding.default_external = Encoding::UTF_8
Encoding.default_internal = Encoding::UTF_8

ipa_folder_path = ARGV[0]
iReSignAppPath = \"#{iReSignAppPath}\"
ipa_path = \"\"
ipa_name_suffix = \"\"
Dir.foreach(ipa_folder_path) do |ipa_name|
	if ipa_name.include? \".ipa\"
		ipa_path = \"\#\{ipa_folder_path\}/\#\{ipa_name\}\"
		ipa_name_suffix = ipa_name.match(/_1\\.0\\.0.*\\.ipa/).to_s
		ipa_name_suffix = ipa_name_suffix.gsub(\".ipa\",\"_resign.ipa\")
		break
	end
end
resign_folder = File.dirname(__FILE__)

"

resign_folder = File.dirname(ruby_file_path)
Dir.foreach(resign_folder) do |mobile_provision_file_name|
	puts mobile_provision_file_name
	if mobile_provision_file_name.include? ".mobileprovision"
		provision_type = "Distribution"
		if mobile_provision_file_name.include? "dev"
			provision_type = "Developer"
		end
		temp_array = getTeamName("#{resign_folder}/#{mobile_provision_file_name}","#{provision_type}")
		certification_name = temp_array[0]
		file_name = temp_array[1]
		$ruby_file.puts("system(\"open -n '\#\{iReSignAppPath\}' --args '\#\{ipa_path\}' '\#\{resign_folder\}/#{mobile_provision_file_name}' '#{certification_name}' '#{file_name}\#\{ipa_name_suffix\}'\")")
		$ruby_file.puts("sleep(5)")
	end
end

$ruby_file.close
